<?php

namespace app\middleware;

use think\Request;
use think\Response;
use Closure;

class Cors
{
    /**
     * 处理请求
     */
    public function handle(Request $request, Closure $next)
    {
        // 预检请求处理
        if ($request->method() === 'OPTIONS') {
            return $this->handlePreflightRequest();
        }

        // 执行请求
        $response = $next($request);

        // 添加CORS头
        return $this->addCorsHeaders($response, $request);
    }

    /**
     * 处理预检请求
     */
    private function handlePreflightRequest()
    {
        $response = response('', 200);

        return $this->addCorsHeaders($response);
    }

    /**
     * 添加CORS头
     */
    private function addCorsHeaders(Response $response, Request $request = null)
    {
        $origin = $request ? $request->header('origin') : '*';

        // 允许的源
        $allowedOrigins = [
            'https://localhost:3000',
            'https://127.0.0.1:3000',
            'https://accountmanage.com',
            'https://www.accountmanage.com',
        ];

        // 在开发环境允许所有源
        if (env('APP_DEBUG', false)) {
            $allowedOrigin = $origin ?: '*';
        } else {
            $allowedOrigin = in_array($origin, $allowedOrigins) ? $origin : '';
        }

        $response->header([
            'Access-Control-Allow-Origin' => $allowedOrigin,
            'Access-Control-Allow-Methods' => 'GET, POST, PUT, DELETE, OPTIONS',
            'Access-Control-Allow-Headers' => 'Content-Type, Authorization, X-Requested-With, Accept, Origin, User-Agent, DNT, Cache-Control, X-Mx-ReqToken, Keep-Alive, X-Requested-With',
            'Access-Control-Allow-Credentials' => 'true',
            'Access-Control-Max-Age' => '86400', // 24小时
        ]);

        return $response;
    }
}